import type { GridColDef } from '@mui/x-data-grid';

import React, { useState, useEffect } from 'react';

import { DataGrid } from '@mui/x-data-grid';
import {
  Box,
  Card,
  Chip,
  Grid,
  Alert,
  Button,
  Select,
  Tooltip,
  MenuItem,
  TextField,
  Typography,
  IconButton,
  InputLabel,
  CardContent,
  FormControl,
  LinearProgress,
} from '@mui/material';

import { retryExecution, getExecutionLogs } from 'src/api/auto-accounting';

import { Iconify } from 'src/components/iconify';

interface ExecutionLog {
  id: string;
  ruleId: string;
  ruleName: string;
  executeTime: string;
  executeResult: string;
  errorMessage?: string;
  cashBookId?: string;
  executionTimeMs?: number;
}

interface PageInfo {
  list: ExecutionLog[];
  pageNum: number;
  pageSize: number;
  total: number;
  pages: number;
  hasNextPage: boolean;
  hasPreviousPage: boolean;
}

export function AutoAccountingExecutionLogs() {
  const [logs, setLogs] = useState<ExecutionLog[]>([]);
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState('');
  const [severity, setSeverity] = useState<'success' | 'error' | 'info' | 'warning'>('info');

  // 分页状态
  const [pageInfo, setPageInfo] = useState<PageInfo>({
    list: [],
    pageNum: 1,
    pageSize: 20,
    total: 0,
    pages: 0,
    hasNextPage: false,
    hasPreviousPage: false,
  });

  // 搜索和过滤状态
  const [ruleIdFilter, setRuleIdFilter] = useState<string>('');
  const [resultFilter, setResultFilter] = useState<string>('');
  const [startDate, setStartDate] = useState<string>('');
  const [endDate, setEndDate] = useState<string>('');

  const columns: GridColDef[] = [
    {
      field: 'ruleName',
      headerName: '规则名称',
      flex: 1.5,
      renderCell: (params) => (
        <Box>
          <Typography variant="subtitle2">{params.value}</Typography>
          <Typography variant="caption" color="text.secondary">
            ID: {params.row.ruleId}
          </Typography>
        </Box>
      ),
    },
    {
      field: 'executeTime',
      headerName: '执行时间',
      flex: 1.5,
      valueFormatter: (params: { value: any }) =>
        params.value ? new Date(params.value as string).toLocaleString('zh-CN') : '-',
    },
    {
      field: 'executeResult',
      headerName: '执行结果',
      flex: 1,
      renderCell: (params) => (
        <Chip
          label={getResultLabel(params.value)}
          size="small"
          color={getResultColor(params.value) as any}
        />
      ),
    },
    {
      field: 'executionTimeMs',
      headerName: '执行时长',
      type: 'number',
      flex: 1,
      valueFormatter: (params: { value: string }) => (params.value ? `${params.value}ms` : '-'),
    },
    {
      field: 'errorMessage',
      headerName: '错误信息',
      flex: 2,
      renderCell: (params) =>
        params.value ? (
          <Tooltip title={params.value}>
            <Typography
              variant="body2"
              color="error.main"
              sx={{ maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis' }}
            >
              {params.value}
            </Typography>
          </Tooltip>
        ) : ('-'),
    },
    {
      field: 'actions',
      headerName: '操作',
      type: 'actions',
      width: 100,
      getActions: (params) => {
        const actions = [];
        if (params.row.executeResult === 'FAILED') {
          actions.push(
            <Tooltip title="重试">
              <IconButton size="small" color="warning" onClick={() => handleRetry(params.row.id)}>
                <Iconify icon="eva:refresh-fill" />
              </IconButton>
            </Tooltip>
          );
        }
        if (params.row.cashBookId) {
          actions.push(
            <Tooltip title="查看记账记录">
              <IconButton size="small" color="primary">
                <Iconify icon="eva:eye-fill" />
              </IconButton>
            </Tooltip>
          );
        }
        return actions;
      },
    },
  ];

  // 获取执行日志
  const fetchLogs = async (page = 1, size = 20) => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        pageNumber: page.toString(),
        pageSize: size.toString(),
      });

      if (ruleIdFilter) params.append('ruleId', ruleIdFilter);
      if (resultFilter) params.append('executeResult', resultFilter);
      if (startDate) params.append('startDate', startDate);
      if (endDate) params.append('endDate', endDate);

      const result = await getExecutionLogs(params);

      if (result.code === '00000') {
        const pageData = result.data.data;
        setLogs(pageData || []);
        setPageInfo({
          ...pageData,
        });
        setMessage('执行日志加载成功');
        setSeverity('success');
      } else {
        setMessage(result.message || '获取执行日志失败');
        setSeverity('error');
      }
    } catch (error) {
      console.error('Error fetching logs:', error);
      setMessage('获取执行日志失败');
      setSeverity('error');
    } finally {
      setLoading(false);
    }
  };

  // 处理分页变化
  const handlePageChange = async (event: React.ChangeEvent<unknown>, page: number) => {
    await fetchLogs(page, pageInfo.pageSize);
  };

  // 处理搜索
  const handleSearch = async () => {
    await fetchLogs(1, pageInfo.pageSize);
  };

  // 重置过滤条件
  const handleReset = async () => {
    setRuleIdFilter('');
    setResultFilter('');
    setStartDate('');
    setEndDate('');
    await fetchLogs(1, pageInfo.pageSize);
  };

  // 重试失败的执行
  const handleRetry = async (logId: string) => {
    try {
      const result = await retryExecution(logId);

      if (result.code === '00000') {
        setMessage('重试执行成功');
        setSeverity('success');
        await fetchLogs(pageInfo.pageNum, pageInfo.pageSize);
      } else {
        setMessage(result.message || '重试执行失败');
        setSeverity('error');
      }
    } catch (error) {
      console.error('Error retrying execution:', error);
      setMessage('重试执行失败');
      setSeverity('error');
    }
  };

  useEffect(() => {
    fetchLogs(1, 20);
  }, []);

  const getResultColor = (result: string) => {
    switch (result) {
      case 'SUCCESS':
        return 'success';
      case 'FAILED':
        return 'error';
      case 'SKIPPED':
        return 'warning';
      default:
        return 'default';
    }
  };

  const getResultLabel = (result: string) => {
    switch (result) {
      case 'SUCCESS':
        return '成功';
      case 'FAILED':
        return '失败';
      case 'SKIPPED':
        return '跳过';
      default:
        return result;
    }
  };

  if (loading && logs.length === 0) {
    return (
      <Box textAlign="center" py={4}>
        <LinearProgress sx={{ mb: 2 }} />
        <Typography>加载中...</Typography>
      </Box>
    );
  }

  return (
    <Box>
      {message && (
        <Alert severity={severity} sx={{ mb: 2 }} onClose={() => setMessage('')}>
          {message}
        </Alert>
      )}

      {/* 搜索和过滤区域 */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Typography variant="h6" sx={{ mb: 2 }}>
            执行日志查询
          </Typography>
          <Grid container spacing={2} alignItems="center">
            <Grid item xs={12} md={3}>
              <TextField
                fullWidth
                size="small"
                placeholder="规则ID..."
                value={ruleIdFilter}
                onChange={(e) => setRuleIdFilter(e.target.value)}
                label="规则ID"
              />
            </Grid>
            <Grid item xs={12} md={2}>
              <FormControl fullWidth size="small">
                <InputLabel>执行结果</InputLabel>
                <Select
                  value={resultFilter}
                  onChange={(e) => setResultFilter(e.target.value)}
                  label="执行结果"
                >
                  <MenuItem value="">全部</MenuItem>
                  <MenuItem value="SUCCESS">成功</MenuItem>
                  <MenuItem value="FAILED">失败</MenuItem>
                  <MenuItem value="SKIPPED">跳过</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} md={2}>
              <TextField
                fullWidth
                size="small"
                type="date"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
                label="开始日期"
                InputLabelProps={{ shrink: true }}
              />
            </Grid>
            <Grid item xs={12} md={2}>
              <TextField
                fullWidth
                size="small"
                type="date"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
                label="结束日期"
                InputLabelProps={{ shrink: true }}
              />
            </Grid>
            <Grid item xs={12} md={3}>
              <Box display="flex" gap={1}>
                <Button
                  variant="contained"
                  onClick={handleSearch}
                  startIcon={<Iconify icon="eva:search-fill" />}
                >
                  查询
                </Button>
                <Button
                  variant="outlined"
                  onClick={handleReset}
                  startIcon={<Iconify icon="eva:refresh-fill" />}
                >
                  重置
                </Button>
              </Box>
            </Grid>
          </Grid>
        </CardContent>
      </Card>

      {/* 执行日志表格 */}
      <Card>
        <CardContent>
          <Box display="flex" justifyContent="space-between" alignItems="center" sx={{ mb: 2 }}>
            <Typography variant="h6">执行日志列表</Typography>
            <Typography variant="body2" color="text.secondary">
              共 {pageInfo.total} 条记录
            </Typography>
          </Box>

          <Box sx={{ height: 650, width: '100%' }}>
            <DataGrid
              rows={logs}
              columns={columns}
              rowCount={pageInfo.total}
              loading={loading}
              pageSizeOptions={[5, 10, 20, 50]}
              paginationMode="server"
              onPaginationModelChange={({ page, pageSize }) => fetchLogs(page + 1, pageSize)}
              getRowId={(row) => row.id || `log-${row.ruleId || row.executeTime || Math.random()}`}
            />
          </Box>
        </CardContent>
      </Card>
    </Box>
  );
}
